using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using System.ComponentModel.DataAnnotations;
using WalkingTec.Mvvm.Core;
using UUIDNext;
using HengTong.Model.Db.SupplyChain.Warehouse;


namespace HengTong.ViewModel.SupplyChain.SysWarehouseVms
{
    public partial class SysWarehouseVm : CrudVm<SysWarehouse>
    {
        [Display(Name = "库管理员")]
        public List<string> SelectedStockersIds { get; set; }

        public SysWarehouseVm()
        {
            SetInclude(x => x.Stockers);
        }

        protected override void InitVM()
        {
            SelectedStockersIds = Entity.Stockers?.Select(x => x.StockerId.ToString()).ToList();
        }

        public override async Task DoAddAsync()
        {
            if (Entity is IBasePoco poco)
            {
                poco.CreateBy = Wtm.LoginUserInfo?.ITCode;
                poco.UpdateBy = Wtm.LoginUserInfo?.ITCode;
                poco.CreateTime = DateTime.Now;
                poco.UpdateTime = DateTime.Now;
            }
            Entity.Stockers = new List<SysWarehouseStocker>();
            if (SelectedStockersIds != null)
            {
                foreach (var id in SelectedStockersIds)
                {
                     SysWarehouseStocker middle = new SysWarehouseStocker();
                    middle.SetPropertyValue("StockerId", id);
                    Entity.Stockers.Add(middle);
                }
            }
            Entity.ID = Uuid.NewDatabaseFriendly(Database.SqlServer);
            await base.DoAddAsync();
        }

        public override async Task DoEditAsync(bool updateAllFields = false)
        {
            if (Entity is IBasePoco poco)
            {
                poco.UpdateBy = Wtm.LoginUserInfo?.ITCode;
                poco.UpdateTime = DateTime.Now;
            }
            Entity.Stockers = new List<SysWarehouseStocker>();
            if(SelectedStockersIds != null )
            {
                 foreach (var item in SelectedStockersIds)
                 {
                     SysWarehouseStocker middle = new SysWarehouseStocker();
                     middle.SetPropertyValue("StockerId", item);
                     Entity.Stockers.Add(middle);
                 }
            }
            await base.DoEditAsync(updateAllFields);
        }

    }
}
